﻿Imports AugmentLib.Database
Imports System.Configuration.ConfigurationManager
Imports AugmentLib.InputOutput.Encryption
Imports AugmentLib.WebComponent
Imports Lsk.Data
Imports Lsk.Business
Imports FlickrNet

Partial Class staffentry
    Inherits System.Web.UI.Page

    Private Sub LoadStaff(ByVal StaffId As String)

        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        Dim TempDT As New Data.DataTable
        Dim listingPercent As Decimal

        objDB.OpenConnection()

        objDB.dbVariable.SQLString = "SELECT StaffId,Initial,UserName,StaffType,Name,ListingPercent,SR,SC,SL,SI,RR,RC,RL,RI,Avatar, Phone, Mobile, Email,Fax,pictureURL, Ren,Description,Area, PropertyType FROM AW_Staff WHERE StatusDelete=0 AND StaffId=@StaffId"
        objDB.AddParameter("StaffId", Data.SqlDbType.UniqueIdentifier, New Guid(StaffId))
        objDB.FillData(TempDT, "AW_Staff", Database.SQLCommandType.NormalString)

        listingPercent = CDbl(getListingPercent(objDB))

        objDB.CloseConnection()

        For Each ReadRow As Data.DataRow In TempDT.Rows
            lblStaffUID.Text = ReadRow.Item("StaffId").ToString
            txtInitial.Text = ReadRow.Item("Initial").ToString
            txtUsername.Text = ReadRow.Item("UserName").ToString
            txtUsername.Enabled = False
            ddlStaffType.SelectedIndex = ReadRow.Item("StaffType").ToString
            txtName.Text = ReadRow.Item("Name").ToString
            If ReadRow.Item("ListingPercent").ToString = "" Then
                txtListingFee.Text = getListingPercent(objDB)
            Else
                txtListingFee.Text = ReadRow.Item("ListingPercent").ToString
            End If
            txtSR.Text = String.Format("{0:#,##0}", ReadRow.Item("SR"))
            txtSC.Text = String.Format("{0:#,##0}", ReadRow.Item("SC"))
            txtSL.Text = String.Format("{0:#,##0}", ReadRow.Item("SL"))
            txtSI.Text = String.Format("{0:#,##0}", ReadRow.Item("SI"))
            txtRR.Text = String.Format("{0:#,##0}", ReadRow.Item("RR"))
            txtRC.Text = String.Format("{0:#,##0}", ReadRow.Item("RC"))
            txtRL.Text = String.Format("{0:#,##0}", ReadRow.Item("RL"))
            txtRI.Text = String.Format("{0:#,##0}", ReadRow.Item("RI"))
            'txtCommision.Text = ReadRow.Item("Commission").ToString
            Dim photoURL As String = ReadRow.Item("pictureURL").ToString
            If String.IsNullOrEmpty(photoURL) Then
                lblAvatarUID.Text = ReadRow.Item("Avatar").ToString
            Else
                lblAvatarUID.Text = photoURL
            End If



            If lblAvatarUID.Text <> "" Then
                imgAvatar.ImageUrl = lblAvatarUID.Text
            Else
                imgAvatar.ImageUrl = "avatar/" & lblAvatarUID.Text


            End If
            txtPhone.Text = ReadRow.Item("Phone").ToString
            txtMobile.Text = ReadRow.Item("Mobile").ToString
            txtEmail.Text = ReadRow.Item("Email").ToString
            txtFax.Text = ReadRow.Item("Fax").ToString
            txtRen.Text = ReadRow.Item("Ren").ToString
            txtDescription.Text = ReadRow.Item("Description").ToString
            txtArea.Text = ReadRow.Item("Area").ToString
            txtPropertyType.Text = ReadRow.Item("PropertyType").ToString
            rfvtxtPassword.Enabled = False
            rfvtxtAvatar.Enabled = False
        Next

        'Added by minginn @ 9/4/11 - load scaling commission
        objDB.OpenConnection()
        TempDT.Clear()
        TempDT.Reset()
        DeclareColumn(TempDT)
        objDB.dbVariable.SQLString = "SELECT CommissionId, AmountFrom, AmountTo, Commission, 'O' AS Status, '1' As Visible FROM AW_Commission WHERE StaffId=@StaffId ORDER BY AmountFrom"
        objDB.AddParameter("StaffId", Data.SqlDbType.UniqueIdentifier, New Guid(StaffId))
        objDB.FillData(TempDT, "AW_Commission", Database.SQLCommandType.NormalString)
        objDB.CloseConnection()
        repCommission.DataSource = TempDT
        repCommission.DataBind()
        VisibilityRepCommission()
        ViewState("DataTable") = TempDT
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Session("StaffId") Is Nothing Then
            Response.Redirect("Default.aspx")
        ElseIf Session.Item("StaffType").ToString = "2" Then
            Response.Redirect("Default.aspx")
        End If

        If Not Page.IsPostBack Then

            'CBEBack.ConfirmText = "You are about to navigate away from this page. " & vbCrLf & "Changes will be discard!"

            If Not Request.QueryString("id") Is Nothing Then
                lblStaffUID.Text = SymmetricDecryptFromHex(Request.QueryString("id"), "augment")
                LoadStaff(lblStaffUID.Text)
            Else
                Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
                objDB.OpenConnection()
                txtListingFee.Text = getListingPercent(objDB)
                objDB.CloseConnection()
            End If

        End If

    End Sub

    Private Function getListingPercent(ByRef ObjDB As Database) As String
        Dim ListingPercentDT As New Data.DataTable
        Dim ListingPercent As String = "0.00"

        ObjDB.dbVariable.SQLString = "SELECT ListingPercent FROM AW_Setting"
        ObjDB.FillData(ListingPercentDT, "ListingPercent", Database.SQLCommandType.NormalString)

        For Each ReadRow As Data.DataRow In ListingPercentDT.Rows
            If ReadRow.Item("ListingPercent").ToString = "" Then
                ListingPercent = "0.00"
            Else
                ListingPercent = ReadRow.Item("ListingPercent").ToString
            End If
        Next
        Return ListingPercent
    End Function

    Private Sub ClearAllFields()
        lblStaffUID.Text = String.Empty
        txtInitial.Text = String.Empty
        txtUsername.Text = String.Empty
        txtPassword.Text = String.Empty
        txtReType.Text = String.Empty
        txtRen.Text = String.Empty
        ddlStaffType.SelectedIndex = 0
        txtName.Text = String.Empty
        txtListingFee.Text = String.Empty
        txtSR.Text = String.Empty
        txtSC.Text = String.Empty
        txtSL.Text = String.Empty
        txtSI.Text = String.Empty
        txtRR.Text = String.Empty
        txtRC.Text = String.Empty
        txtRL.Text = String.Empty
        txtRI.Text = String.Empty
        'txtCommision.Text = String.Empty
        lblAvatarUID.Text = String.Empty
        imgAvatar.ImageUrl = String.Empty
        txtPhone.Text = String.Empty
        txtMobile.Text = String.Empty
        txtEmail.Text = String.Empty
        txtDescription.Text = String.Empty
        txtArea.Text = String.Empty
        txtPropertyType.Text = String.Empty
    End Sub

    Protected Sub BtnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))

        Dim ExistUserName As String
        If lblStaffUID.Text = "" Then
            ExistUserName = IsUserNameExist()
            'Check if username Exist
            If ExistUserName = "N" Then
                lblExistUsernameError.Text = "<br />Username already exists"
                Exit Sub
            ElseIf ExistUserName <> "" Then
                'TODO : Should ask if wan to reactivate the user
                lblStaffUID.Text = ExistUserName
            End If
        End If
        If lblStaffUID.Text = "" Then
            'Insert 
            Dim UploadedImg As String = ""
            Dim flickInfo As New PhotoInfo
            Try

                If filAvatar.HasFile Then
                    Dim Avatarimg As HttpPostedFile = filAvatar.PostedFile
                    If System.IO.Path.GetExtension(filAvatar.FileName).ToLower() <> ".jpg" Then
                        lblMsgError.Text = "Please upload only JPG files for Avatar"
                        divError.Visible = True
                        Exit Sub
                    Else
                        Dim objImgComp As New ImageComp
                        UploadedImg = objImgComp.UploadSingleImage(Avatarimg, "avatar", False, 0)


                        'Upload to Flickr

                        Dim pMgr As New PhotoManager
                        Dim staff As New AW_Staff
                        lblStaffUID.Text = Guid.NewGuid.ToString
                        staff.StaffId = New Guid(lblStaffUID.Text)
                        staff.UserName = txtUsername.Text.Trim.ToUpper
                        staff.Email = txtEmail.Text.Trim
                        staff.Ren = txtRen.Text.Trim
                        staff.Avatar = UploadedImg.ToString

                        flickInfo = pMgr.UploadStaff(Avatarimg.InputStream, staff)

                    End If
                End If
            Catch ex As Exception
                lblMsgError.Text = ex.Message
                divError.Visible = True
                Exit Sub
            End Try

            If UploadedImg <> "" Then
                Try
                    objDB.OpenConnection()
                    'Added by minginn @ 9/4/11 Transaction to also insert scaling commission to the database
                    objDB.InitDbTrans()
                    objDB.dbVariable.SQLString = "INSERT INTO AW_Staff (StaffId,Initial,UserName,Password,StaffType,Name,ListingPercent,SR,SC,SL,SI,RR,RC,RL,RI,Avatar, Phone, Mobile, Email,Fax,CreateDate,StatusDelete,PhotoId,pictureURL,LargeUrl,MediumUrl,SmallUrl, Ren, Description, Area, PropertyType) VALUES (@StaffId,@Initial,@UserName,@Password,@StaffType,@Name,@ListingPercent,@SR,@SC,@SL,@SI,@RR,@RC,@RL,@RI,@Avatar, @Phone, @Mobile, @Email,@Fax,@CreateDate,@StatusDelete,@PhotoId,@pictureURL,@LargeUrl,@MediumUrl,@SmallUrl, @Ren, @Description, @Area, @PropertyType)"
                    ' lblStaffUID.Text = Guid.NewGuid.ToString
                    objDB.AddParameter("StaffId", Data.SqlDbType.UniqueIdentifier, New Guid(lblStaffUID.Text))
                    objDB.AddParameter("Initial", Data.SqlDbType.NVarChar, txtInitial.Text.Trim.ToUpper)
                    objDB.AddParameter("UserName", Data.SqlDbType.NVarChar, txtUsername.Text.Trim.ToUpper)
                    objDB.AddParameter("Ren", Data.SqlDbType.NVarChar, txtRen.Text.Trim.ToUpper)
                    objDB.AddParameter("Description", Data.SqlDbType.NVarChar, txtDescription.Text.Trim.ToUpper)
                    objDB.AddParameter("Area", Data.SqlDbType.NVarChar, txtArea.Text.Trim.ToUpper)
                    objDB.AddParameter("PropertyType", Data.SqlDbType.NVarChar, txtPropertyType.Text.Trim.ToUpper)
                    objDB.AddParameter("Password", Data.SqlDbType.NChar, SymmetricEncrypt(txtPassword.Text, "augment"))
                    objDB.AddParameter("StaffType", Data.SqlDbType.Int, ddlStaffType.SelectedIndex)
                    objDB.AddParameter("Name", Data.SqlDbType.NVarChar, txtName.Text.Trim.ToUpper)
                    objDB.AddParameter("ListingPercent", Data.SqlDbType.Decimal, txtListingFee.Text.Trim)
                    objDB.AddParameter("SR", Data.SqlDbType.Decimal, txtSR.Text.Trim)
                    objDB.AddParameter("SC", Data.SqlDbType.Decimal, txtSC.Text.Trim)
                    objDB.AddParameter("SL", Data.SqlDbType.Decimal, txtSL.Text.Trim)
                    objDB.AddParameter("SI", Data.SqlDbType.Decimal, txtSI.Text.Trim)
                    objDB.AddParameter("RR", Data.SqlDbType.Decimal, txtRR.Text.Trim)
                    objDB.AddParameter("RC", Data.SqlDbType.Decimal, txtRC.Text.Trim)
                    objDB.AddParameter("RL", Data.SqlDbType.Decimal, txtRL.Text.Trim)
                    objDB.AddParameter("RI", Data.SqlDbType.Decimal, txtRI.Text.Trim)
                    'objDB.AddParameter("Commission", Data.SqlDbType.Decimal, txtCommision.Text.Trim)
                    objDB.AddParameter("Avatar", Data.SqlDbType.NVarChar, UploadedImg)
                    objDB.AddParameter("Phone", Data.SqlDbType.NVarChar, txtPhone.Text.Trim)
                    objDB.AddParameter("Mobile", Data.SqlDbType.NVarChar, txtMobile.Text.Trim)
                    objDB.AddParameter("Fax", Data.SqlDbType.NVarChar, txtFax.Text.Trim)
                    objDB.AddParameter("Email", Data.SqlDbType.NVarChar, txtEmail.Text.Trim)
                    objDB.AddParameter("CreateDate", Data.SqlDbType.DateTime, Now)
                    objDB.AddParameter("StatusDelete", Data.SqlDbType.TinyInt, 0)
                    'Photo URL from FLICKR
                    objDB.AddParameter("PhotoId", Data.SqlDbType.NVarChar, flickInfo.PhotoId)
                    objDB.AddParameter("pictureURL", Data.SqlDbType.NVarChar, flickInfo.OriginalUrl)
                    objDB.AddParameter("LargeUrl", Data.SqlDbType.NVarChar, flickInfo.LargeUrl)
                    objDB.AddParameter("MediumUrl", Data.SqlDbType.NVarChar, flickInfo.MediumUrl)
                    objDB.AddParameter("SmallUrl", Data.SqlDbType.NVarChar, flickInfo.SmallUrl)

                    objDB.ExecuteQuery()
                    'to add in scale commission
                    If AddScalingCommission(objDB) = 1 Then
                        objDB.DbTransCommit()
                        objDB.CloseConnection()

                        Session.Add("entry", txtName.Text.Trim)
                        Response.Redirect("staff.aspx", False)
                    Else
                        If objDB.dbVariable.objConn.State = Data.ConnectionState.Open Then
                            objDB.DbTransRollback()
                            objDB.CloseConnection()
                        End If
                        If UploadedImg <> "" Then
                            Dim objImgComp As New ImageComp
                            objImgComp.DeleteSingleFile("avatar", UploadedImg)
                        End If
                        divError.Visible = True
                        lblStaffUID.Text = String.Empty
                        Exit Sub
                    End If
                Catch ex As Exception
                    If objDB.dbVariable.objConn.State = Data.ConnectionState.Open Then
                        objDB.DbTransRollback()
                        objDB.CloseConnection()
                    End If
                    If UploadedImg <> "" Then
                        Dim objImgComp As New ImageComp
                        objImgComp.DeleteSingleFile("avatar", UploadedImg)
                    End If
                    lblStaffUID.Text = String.Empty
                    lblMsgError.Text = ex.Message
                    divError.Visible = True
                End Try
            Else
                lblMsgError.Text = "Please upload only JPG files for Avatar"
                divError.Visible = True
                Exit Sub
            End If
        Else
            'Update 
            Dim UploadedImg As String = ""
            Dim flickInfo As New PhotoInfo
            Try
                If filAvatar.HasFile Then
                    Dim Avatarimg As HttpPostedFile = filAvatar.PostedFile
                    If System.IO.Path.GetExtension(filAvatar.FileName).ToLower() <> ".jpg" Then
                        lblMsgError.Text = "Please upload only JPG files for Avatar"
                        divError.Visible = True
                        Exit Sub
                    Else
                        Dim objImgComp As New ImageComp
                        UploadedImg = objImgComp.UploadSingleImage(Avatarimg, "avatar", False, 0)

                        'Upload to Flickr

                        Dim pMgr As New PhotoManager
                        Dim staff As New AW_Staff

                        staff.StaffId = New Guid(lblStaffUID.Text)
                        staff.UserName = txtUsername.Text.Trim.ToUpper
                        staff.Email = txtEmail.Text.Trim
                        staff.Avatar = UploadedImg.ToString

                        flickInfo = pMgr.UploadStaff(Avatarimg.InputStream, staff)
                    End If
                End If
            Catch ex As Exception
                lblMsgError.Text = ex.Message
                divError.Visible = True
                Exit Sub
            End Try

            Try
                objDB.OpenConnection()
                objDB.InitDbTrans()
                If UploadedImg <> "" Then
                    If txtPassword.Text <> "" Then
                        objDB.dbVariable.SQLString = "@UPDATE AW_Staff SET Initial=@Initial,Password=@Password,StaffType=@StaffType,Name=@Name,ListingPercent=@ListingPercent,SR=@SR,SC=@SC,SL=@SL,SI=@SI,RR=@RR,RC=@RC,RL=@RL,RI=@RI,Avatar=@Avatar,Phone=@Phone,Mobile=@Mobile,Fax=@Fax,Email=@Email,StatusDelete=@StatusDelete, pictureURL=@pictureURL, LargeUrl=@LargeURL,PhotoId=@PhotoId,MediumUrl=@MediumUrl, SmallUrl=@SmallUrl,Ren=@Ren,Description=@Description,Area=@Area,PropertyType=@PropertyType WHERE StaffId=@StaffId"
                        objDB.AddParameter("Password", Data.SqlDbType.NVarChar, SymmetricEncrypt(txtPassword.Text.Trim, "augment"))
                        objDB.AddParameter("Avatar", Data.SqlDbType.NVarChar, UploadedImg)

                        'Photo URL from FLICKR
                        objDB.AddParameter("PhotoId", Data.SqlDbType.NVarChar, flickInfo.PhotoId)
                        objDB.AddParameter("pictureURL", Data.SqlDbType.NVarChar, flickInfo.OriginalUrl)
                        objDB.AddParameter("LargeUrl", Data.SqlDbType.NVarChar, flickInfo.LargeUrl)
                        objDB.AddParameter("MediumUrl", Data.SqlDbType.NVarChar, flickInfo.MediumUrl)
                        objDB.AddParameter("SmallUrl", Data.SqlDbType.NVarChar, flickInfo.SmallUrl)
                    Else
                        objDB.dbVariable.SQLString = "UPDATE AW_Staff SET Initial=@Initial,StaffType=@StaffType,Name=@Name,ListingPercent=@ListingPercent,SR=@SR,SC=@SC,SL=@SL,SI=@SI,RR=@RR,RC=@RC,RL=@RL,RI=@RI,Avatar=@Avatar,Phone=@Phone,Mobile=@Mobile,Fax=@Fax,Email=@Email,StatusDelete=@StatusDelete,pictureURL=@pictureURL, LargeUrl=@LargeURL,PhotoId=@PhotoId,MediumUrl=@MediumUrl, SmallUrl=@SmallUrl,Ren=@Ren,Description=@Description,Area=@Area,PropertyType=@PropertyType WHERE StaffId=@StaffId"
                        objDB.AddParameter("Avatar", Data.SqlDbType.NVarChar, UploadedImg)

                        'Photo URL from FLICKR
                        objDB.AddParameter("PhotoId", Data.SqlDbType.NVarChar, flickInfo.PhotoId)
                        objDB.AddParameter("pictureURL", Data.SqlDbType.NVarChar, flickInfo.OriginalUrl)
                        objDB.AddParameter("LargeUrl", Data.SqlDbType.NVarChar, flickInfo.LargeUrl)
                        objDB.AddParameter("MediumUrl", Data.SqlDbType.NVarChar, flickInfo.MediumUrl)
                        objDB.AddParameter("SmallUrl", Data.SqlDbType.NVarChar, flickInfo.SmallUrl)
                    End If
                Else
                    If txtPassword.Text <> "" Then
                        objDB.dbVariable.SQLString = "UPDATE AW_Staff SET Initial=@Initial,Password=@Password,StaffType=@StaffType,Name=@Name,ListingPercent=@ListingPercent,SR=@SR,SC=@SC,SL=@SL,SI=@SI,RR=@RR,RC=@RC,RL=@RL,RI=@RI,Phone=@Phone,Mobile=@Mobile,Fax=@Fax,Email=@Email,StatusDelete=@StatusDelete,Ren=@Ren,Description=@Description,Area=@Area,PropertyType=@PropertyType WHERE StaffId=@StaffId"
                        objDB.AddParameter("Password", Data.SqlDbType.NVarChar, SymmetricEncrypt(txtPassword.Text.Trim, "augment"))
                    Else
                        objDB.dbVariable.SQLString = "UPDATE AW_Staff SET Initial=@Initial,StaffType=@StaffType,Name=@Name,ListingPercent=@ListingPercent,SR=@SR,SC=@SC,SL=@SL,SI=@SI,RR=@RR,RC=@RC,RL=@RL,RI=@RI,Phone=@Phone,Mobile=@Mobile,Fax=@Fax,Email=@Email,StatusDelete=@StatusDelete,Ren=@Ren,Description=@Description,Area=@Area,PropertyType=@PropertyType WHERE StaffId=@StaffId"
                    End If
                End If

                objDB.AddParameter("Initial", Data.SqlDbType.NVarChar, txtInitial.Text.Trim.ToUpper)
                objDB.AddParameter("StaffType", Data.SqlDbType.TinyInt, ddlStaffType.SelectedIndex)
                objDB.AddParameter("Name", Data.SqlDbType.NVarChar, txtName.Text.Trim.ToUpper)
                objDB.AddParameter("Ren", Data.SqlDbType.NVarChar, txtRen.Text.Trim.ToUpper)
                objDB.AddParameter("Description", Data.SqlDbType.NVarChar, txtDescription.Text.Trim)
                objDB.AddParameter("Area", Data.SqlDbType.NVarChar, txtArea.Text.Trim)
                objDB.AddParameter("PropertyType", Data.SqlDbType.NVarChar, txtPropertyType.Text.Trim)
                objDB.AddParameter("SR", Data.SqlDbType.Decimal, txtSR.Text.Trim)
                objDB.AddParameter("SC", Data.SqlDbType.Decimal, txtSC.Text.Trim)
                objDB.AddParameter("SL", Data.SqlDbType.Decimal, txtSL.Text.Trim)
                objDB.AddParameter("SI", Data.SqlDbType.Decimal, txtSI.Text.Trim)
                objDB.AddParameter("RR", Data.SqlDbType.Decimal, txtRR.Text.Trim)
                objDB.AddParameter("RC", Data.SqlDbType.Decimal, txtRC.Text.Trim)
                objDB.AddParameter("RL", Data.SqlDbType.Decimal, txtRC.Text.Trim)
                objDB.AddParameter("RI", Data.SqlDbType.Decimal, txtRI.Text.Trim)
                objDB.AddParameter("ListingPercent", Data.SqlDbType.Decimal, txtListingFee.Text.Trim)
                'objDB.AddParameter("Commission", Data.SqlDbType.Decimal, txtCommision.Text.Trim)
                objDB.AddParameter("Phone", Data.SqlDbType.NVarChar, txtPhone.Text.Trim)
                objDB.AddParameter("Mobile", Data.SqlDbType.NVarChar, txtMobile.Text.Trim)
                objDB.AddParameter("Fax", Data.SqlDbType.NVarChar, txtFax.Text.Trim)
                objDB.AddParameter("Email", Data.SqlDbType.NVarChar, txtEmail.Text.Trim)
                objDB.AddParameter("StatusDelete", Data.SqlDbType.TinyInt, 0)
                objDB.AddParameter("StaffId", Data.SqlDbType.UniqueIdentifier, New Guid(lblStaffUID.Text))
                objDB.ExecuteQuery()
                'to add in scale commission
                If AddScalingCommission(objDB) = 1 Then
                    objDB.DbTransCommit()
                    objDB.CloseConnection()

                    If UploadedImg <> "" Then
                        Dim objImgComp As New ImageComp
                        objImgComp.DeleteSingleFile("avatar", lblAvatarUID.Text)
                    End If
                    Session.Add("entryU", txtName.Text.Trim)
                    Response.Redirect("staff.aspx", False)
                Else
                    If objDB.dbVariable.objConn.State = Data.ConnectionState.Open Then
                        objDB.DbTransRollback()
                        objDB.CloseConnection()
                    End If
                    If UploadedImg <> "" Then
                        Dim objImgComp As New ImageComp
                        objImgComp.DeleteSingleFile("avatar", UploadedImg)
                    End If
                    divError.Visible = True
                    Exit Sub
                End If
            Catch ex As Exception
                If objDB.dbVariable.objConn.State = Data.ConnectionState.Open Then
                    objDB.DbTransRollback()
                    objDB.CloseConnection()
                End If
                If UploadedImg <> "" Then
                    Dim objImgComp As New ImageComp
                    objImgComp.DeleteSingleFile("avatar", UploadedImg)
                End If
                lblMsgError.Text = ex.Message
                divError.Visible = True
                Exit Sub
            End Try
        End If
    End Sub

    Private Function AddScalingCommission(ByVal objdb As Database) As Integer
        If txtAmountFrom.Text <> "" Or txtAmountTo.Text <> "" Or txtCommission.Text <> "" Then
            AddNewRow()
        End If
        Dim myDT As New Data.DataTable
        myDT = CType(ViewState("DataTable"), Data.DataTable)
        If Not myDT Is Nothing Then
            For Each myrow As Data.DataRow In myDT.Rows
                If myrow.Item("Status") = "N" And myrow.Item("Visible") = "1" Then
                    'insert
                    objdb.dbVariable.SQLString = "INSERT INTO AW_Commission (CommissionId,StaffId,AmountFrom,AmountTo,Commission) " & _
                    "VALUES (@CommissionId,@StaffId,@AmountFrom,@AmountTo,@Commission)"
                    objdb.AddParameter("CommissionId", Data.SqlDbType.UniqueIdentifier, New Guid(myrow.Item("CommissionId").ToString))
                    objdb.AddParameter("StaffId", Data.SqlDbType.UniqueIdentifier, New Guid(lblStaffUID.Text))
                    objdb.AddParameter("AmountFrom", Data.SqlDbType.Decimal, CDec(myrow.Item("AmountFrom")))
                    objdb.AddParameter("AmountTo", Data.SqlDbType.Decimal, CDec(myrow.Item("AmountTo")))
                    objdb.AddParameter("Commission", Data.SqlDbType.Decimal, CDec(myrow.Item("Commission")))
                    objdb.ExecuteQuery()
                Else
                    If myrow.Item("Visible") = "0" Then
                        'delete
                        objdb.dbVariable.SQLString = "DELETE AW_Commission WHERE CommissionId=@CommissionId"
                        objdb.AddParameter("CommissionId", Data.SqlDbType.UniqueIdentifier, New Guid(myrow.Item("CommissionId").ToString))
                        objdb.ExecuteQuery()
                    Else
                        'update
                        objdb.dbVariable.SQLString = "UPDATE AW_Commission SET AmountFrom=@AmountFrom, AmountTo=@AmountTo, Commission=@Commission " & _
                        "WHERE CommissionId=@CommissionId"
                        objdb.AddParameter("CommissionId", Data.SqlDbType.UniqueIdentifier, New Guid(myrow.Item("CommissionId").ToString))
                        objdb.AddParameter("StaffId", Data.SqlDbType.UniqueIdentifier, New Guid(lblStaffUID.Text))
                        objdb.AddParameter("AmountFrom", Data.SqlDbType.Decimal, CDec(myrow.Item("AmountFrom")))
                        objdb.AddParameter("AmountTo", Data.SqlDbType.Decimal, CDec(myrow.Item("AmountTo")))
                        objdb.AddParameter("Commission", Data.SqlDbType.Decimal, CDec(myrow.Item("Commission")))
                        objdb.ExecuteQuery()
                    End If

                End If
            Next
            Return 1
        Else
            lblMsgError.Text = "Please fill in the commission"
            Return 0
        End If

    End Function

    Private Function IsUserNameExist() As String
        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        Dim TempDT As New Data.DataTable
        Dim strStaff As String = String.Empty
        objDB.OpenConnection()

        'objDB.dbVariable.SQLString = "SELECT UserName FROM AW_Staff WHERE StatusDelete=0 AND UserName=@UserName"
        objDB.dbVariable.SQLString = "SELECT UserName, StatusDelete, StaffId FROM AW_Staff WHERE UserName=@UserName"
        objDB.AddParameter("UserName", Data.SqlDbType.NVarChar, txtUsername.Text.Trim.ToUpper)
        objDB.FillData(TempDT, "AW_Staff", Database.SQLCommandType.NormalString)
        objDB.CloseConnection()

        If TempDT.Rows.Count >= 1 Then
            For Each row As Data.DataRow In TempDT.Rows
                If row.Item("StatusDelete").ToString = "0" Then
                    strStaff = "N"
                Else
                    strStaff = row.Item("StaffId").ToString
                End If
            Next
        Else
            strStaff = ""
        End If
        Return strStaff
    End Function

    Protected Sub btnVerify_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnVerify.Click
        If IsUserNameExist() Then
            lblExistUsernameError.Text = "<br />Username already exists"
        Else
            lblExistUsernameError.Text = ""
        End If
    End Sub

    Protected Sub btnAddCommission_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddCommission.Click
        If txtAmountFrom.Text <> "" And txtAmountTo.Text <> "" And txtCommission.Text <> "" Then
            AddNewRow()
            txtAmountFrom.Text = ""
            txtAmountTo.Text = ""
            txtCommission.Text = ""
        Else
            'do something
        End If
    End Sub

    Private Sub AddNewRow()
        Dim MyDT As New Data.DataTable

        If ViewState("DataTable") Is Nothing Then
            DeclareColumn(MyDT)
            Dim MyRow As Data.DataRow
            MyRow = MyDT.NewRow()
            MyRow(0) = Guid.NewGuid
            MyRow(1) = txtAmountFrom.Text.Trim
            MyRow(2) = txtAmountTo.Text.Trim
            MyRow(3) = txtCommission.Text.Trim
            MyRow(4) = "N"
            MyRow(5) = "1"
            MyDT.Rows.Add(MyRow)
        Else
            MyDT = CType(ViewState("DataTable"), Data.DataTable)
            Dim MyRow As Data.DataRow
            MyRow = MyDT.NewRow()
            MyRow(0) = Guid.NewGuid
            MyRow(1) = txtAmountFrom.Text.Trim
            MyRow(2) = txtAmountTo.Text.Trim
            MyRow(3) = txtCommission.Text.Trim
            MyRow(4) = "N"
            MyRow(5) = "1"
            MyDT.Rows.Add(MyRow)
        End If
        ViewState("DataTable") = MyDT
        repCommission.DataSource = MyDT
        repCommission.DataBind()
        VisibilityRepCommission()
    End Sub

    Private Sub DeclareColumn(ByVal MyDT As Data.DataTable)
        Dim CommissionId As Data.DataColumn = New Data.DataColumn("CommissionId")
        CommissionId.DataType = System.Type.GetType("System.String")
        MyDT.Columns.Add(CommissionId)
        Dim AmountFrom As Data.DataColumn = New Data.DataColumn("AmountFrom")
        AmountFrom.DataType = System.Type.GetType("System.Decimal")
        MyDT.Columns.Add(AmountFrom)
        Dim AmountTo As Data.DataColumn = New Data.DataColumn("AmountTo")
        AmountTo.DataType = System.Type.GetType("System.Decimal")
        MyDT.Columns.Add(AmountTo)
        Dim Commission As Data.DataColumn = New Data.DataColumn("Commission")
        Commission.DataType = System.Type.GetType("System.Decimal")
        MyDT.Columns.Add(Commission)
        Dim Status As Data.DataColumn = New Data.DataColumn("Status")
        Status.DataType = System.Type.GetType("System.String")
        MyDT.Columns.Add(Status)
        Dim Visible As Data.DataColumn = New Data.DataColumn("Visible")
        Visible.DataType = System.Type.GetType("System.String")
        MyDT.Columns.Add(Visible)
    End Sub

    Protected Sub repCommission_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles repCommission.ItemCommand
        If e.CommandName.ToUpper = "SAVE" Then
            Dim MyDT As New Data.DataTable
            'Dim MyRow() As Data.DataRow

            MyDT = CType(ViewState("DataTable"), Data.DataTable)
            'MyRow = MyDT.Select("CommissionId = '" & CType(repCommission.Items(e.CommandArgument).FindControl("lblhidRepCommissionId"), Label).Text & "'")
            'If MyRow IsNot Nothing AndAlso MyRow.Length > 0 Then
            '    For i As Integer = 0 To MyRow.Length - 1
            MyDT.Rows(e.CommandArgument)(0) = CType(repCommission.Items(e.CommandArgument).FindControl("lblhidRepCommissionId"), Label).Text
            MyDT.Rows(e.CommandArgument)(1) = CType(repCommission.Items(e.CommandArgument).FindControl("txtRepAmountFrom"), TextBox).Text
            MyDT.Rows(e.CommandArgument)(2) = CType(repCommission.Items(e.CommandArgument).FindControl("txtRepAmountTo"), TextBox).Text
            MyDT.Rows(e.CommandArgument)(3) = CType(repCommission.Items(e.CommandArgument).FindControl("txtRepCommission"), TextBox).Text
            MyDT.Rows(e.CommandArgument)(4) = MyDT.Rows(e.CommandArgument)(4).ToString
            MyDT.Rows(e.CommandArgument)(5) = MyDT.Rows(e.CommandArgument)(5).ToString
            'Next
            MyDT.AcceptChanges()
            'End If
            ViewState("DataTable") = MyDT
            repCommission.DataSource = MyDT
            repCommission.DataBind()
            VisibilityRepCommission()
        ElseIf e.CommandName.ToUpper = "CANCEL" Then
            Dim lbtRepAmountFrom, lbtRepAmountTo, lbtRepCommission As LinkButton
            Dim txtRepAmountFrom, txtRepAmountTo, txtRepCommission As TextBox
            Dim btnMinusCommission, btnSaveCommission, btnCancelCommission As Button
            lbtRepAmountFrom = CType(repCommission.Items(e.CommandArgument).FindControl("lbtRepAmountFrom"), LinkButton)
            lbtRepAmountTo = CType(repCommission.Items(e.CommandArgument).FindControl("lbtRepAmountTo"), LinkButton)
            lbtRepCommission = CType(repCommission.Items(e.CommandArgument).FindControl("lbtRepCommission"), LinkButton)
            txtRepAmountFrom = CType(repCommission.Items(e.CommandArgument).FindControl("txtRepAmountFrom"), TextBox)
            txtRepAmountTo = CType(repCommission.Items(e.CommandArgument).FindControl("txtRepAmountTo"), TextBox)
            txtRepCommission = CType(repCommission.Items(e.CommandArgument).FindControl("txtRepCommission"), TextBox)
            btnMinusCommission = CType(repCommission.Items(e.CommandArgument).FindControl("btnMinusCommission"), Button)
            btnSaveCommission = CType(repCommission.Items(e.CommandArgument).FindControl("btnSaveCommission"), Button)
            btnCancelCommission = CType(repCommission.Items(e.CommandArgument).FindControl("btnCancelCommission"), Button)
            txtRepAmountFrom.Visible = False
            txtRepAmountTo.Visible = False
            txtRepCommission.Visible = False
            btnSaveCommission.Visible = False
            btnCancelCommission.Visible = False
            lbtRepAmountFrom.Visible = True
            lbtRepAmountTo.Visible = True
            lbtRepCommission.Visible = True
            btnMinusCommission.Visible = True
        ElseIf e.CommandName.ToUpper = "MINUS" Then
            'Dim MyDT As New Data.DataTable
            'Dim MyRow() As Data.DataRow
            'MyDT = CType(ViewState("DataTable"), Data.DataTable)
            'MyRow = MyDT.Select("CommissionId = '" & CType(repCommission.Items(e.CommandArgument).FindControl("lblhidRepCommissionId"), Label).Text & "'")

            'If MyRow IsNot Nothing AndAlso MyRow.Length > 0 Then
            '    For i As Integer = 0 To MyRow.Length - 1
            '        MyRow(i).Delete()
            '    Next
            '    MyDT.AcceptChanges()
            'End If
            'ViewState("DataTable") = MyDT
            'repCommission.DataSource = MyDT
            'repCommission.DataBind()
            Dim MyDT As New Data.DataTable
            'Dim MyRow() As Data.DataRow

            MyDT = CType(ViewState("DataTable"), Data.DataTable)
            'MyRow = MyDT.Select("CommissionId = '" & CType(repCommission.Items(e.CommandArgument).FindControl("lblhidRepCommissionId"), Label).Text & "'")
            'If MyRow IsNot Nothing AndAlso MyRow.Length > 0 Then
            '    For i As Integer = 0 To MyRow.Length - 1
            MyDT.Rows(e.CommandArgument)(0) = MyDT.Rows(e.CommandArgument)(0).ToString
            MyDT.Rows(e.CommandArgument)(1) = MyDT.Rows(e.CommandArgument)(1).ToString
            MyDT.Rows(e.CommandArgument)(2) = MyDT.Rows(e.CommandArgument)(2).ToString
            MyDT.Rows(e.CommandArgument)(3) = MyDT.Rows(e.CommandArgument)(3).ToString
            MyDT.Rows(e.CommandArgument)(4) = MyDT.Rows(e.CommandArgument)(4).ToString
            MyDT.Rows(e.CommandArgument)(5) = "0"
            'Next
            MyDT.AcceptChanges()
            'End If
            ViewState("DataTable") = MyDT
            repCommission.DataSource = MyDT
            repCommission.DataBind()
            VisibilityRepCommission()
        ElseIf e.CommandName.ToUpper = "EDIT" Then
            Dim lbtRepAmountFrom, lbtRepAmountTo, lbtRepCommission As LinkButton
            Dim txtRepAmountFrom, txtRepAmountTo, txtRepCommission As TextBox
            Dim btnMinusCommission, btnSaveCommission, btnCancelCommission As Button
            lbtRepAmountFrom = CType(repCommission.Items(e.CommandArgument).FindControl("lbtRepAmountFrom"), LinkButton)
            lbtRepAmountTo = CType(repCommission.Items(e.CommandArgument).FindControl("lbtRepAmountTo"), LinkButton)
            lbtRepCommission = CType(repCommission.Items(e.CommandArgument).FindControl("lbtRepCommission"), LinkButton)
            txtRepAmountFrom = CType(repCommission.Items(e.CommandArgument).FindControl("txtRepAmountFrom"), TextBox)
            txtRepAmountTo = CType(repCommission.Items(e.CommandArgument).FindControl("txtRepAmountTo"), TextBox)
            txtRepCommission = CType(repCommission.Items(e.CommandArgument).FindControl("txtRepCommission"), TextBox)
            btnMinusCommission = CType(repCommission.Items(e.CommandArgument).FindControl("btnMinusCommission"), Button)
            btnSaveCommission = CType(repCommission.Items(e.CommandArgument).FindControl("btnSaveCommission"), Button)
            btnCancelCommission = CType(repCommission.Items(e.CommandArgument).FindControl("btnCancelCommission"), Button)
            txtRepAmountFrom.Visible = True
            txtRepAmountTo.Visible = True
            txtRepCommission.Visible = True
            btnSaveCommission.Visible = True
            btnCancelCommission.Visible = True
            lbtRepAmountFrom.Visible = False
            lbtRepAmountTo.Visible = False
            lbtRepCommission.Visible = False
            btnMinusCommission.Visible = False
        End If
    End Sub

    Private Sub VisibilityRepCommission()
        For Each repitem As RepeaterItem In repCommission.Items
            If CType(repitem.FindControl("lblhidRepVisible"), Label).Text = "0" Then
                repitem.Visible = False
            Else
                repitem.Visible = True
            End If
        Next
    End Sub

    Protected Sub btnBack_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBack.Click
        If Session("Back") Is Nothing Then
            Response.Redirect("Staff.aspx")
        Else
            Dim strBack As String = Session("Back").ToString
            Dim arr() As String = strBack.Split("ڡ")
            Response.Redirect(arr(0).ToString)
        End If
    End Sub



End Class
